﻿<%@ WebHandler Language="C#" Class="HandlerUserProfile" %>

using System;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using Newtonsoft.Json;
using System.Web.Security;

public class HandlerUserProfile : IHttpHandler {
    
    public void ProcessRequest (HttpContext context) {
        string strconn = LinkToDatabase.strConn;/*App_Code->UserClass.cs*/
        string strcmd = "";
        string type = context.Request.Form["type"];
        SqlCommand cmd = null;
        int UserId = Convert.ToInt32(context.Request.Cookies["u_id"].Value);
        using (SqlConnection conn = new SqlConnection(strconn))
        {
            switch (type)
            {
                //1=======================================================================
                case "1":
                    strcmd = @"select 
                                     user_first_name as Fname
                                    ,user_last_name as Lname
									,datepart(DAY,user_birthday) as BDay
									,datepart(MONTH,user_birthday) as BMonth
									,datepart(YEAR,user_birthday) as BYear
                                    ,user_mobile_phone as Phone 
                                    ,user_email as Email
									,user_picture as Picture
                              from [UBOX].[dbo].[user]
                              where user_id=@ID
                            ";
                    break;
                //2=======================================================================
                case "2":
                     strcmd = @"update [UBOX].[dbo].[user]set user_birthday=@Birthday ";
                     if (context.Request.Form["type2"] == "a") {
                         strcmd += ",user_picture=@Picture ";
                     }
                         strcmd += ",user_first_name=@Fname";
                         strcmd += ",user_last_name=@Lname ";
                         strcmd += ",user_email=@Email ";
                         strcmd += ",user_mobile_phone=@Phone ";
                     strcmd += "WHERE [user_id]=@ID set @Result = @@rowcount";
                    break;
                //3=======================================================================
                case "3":
                    strcmd += @"
                              update [dbo].[user] 
                              set user_password=@Password
                                 ,user_password_Random=@Random
                              Where user_id=@Id
	                      set @Result = @@rowcount
                        ";

                    break;//@@rowcount上一個操作影響行數
            }
            using (SqlDataAdapter da = new SqlDataAdapter(strcmd, conn))
            {
                SqlParameter Result;
                Result = new SqlParameter("@Result", SqlDbType.Bit);
                Result.Direction = ParameterDirection.Output;
                switch (type)
                {
                    //1=======================================================================
                    case "1":
                        //input
                        da.SelectCommand.Parameters.AddWithValue("@ID", UserId);
                        break;
                    //2=======================================================================
                    case "2":
                        cmd = new SqlCommand(strcmd, conn);
                        cmd.CommandType = CommandType.Text;
                        //input
                        cmd.Parameters.AddWithValue("@ID", UserId);
                        cmd.Parameters.AddWithValue
                            ("@Birthday"
                            ,context.Request.Form["year"]+"-"
                            +context.Request.Form["month"]+"-"
                            +context.Request.Form["day"]);
                            if (context.Request.Form["type2"] == "a"){
                                byte[] picture = null;
                                HttpPostedFile file = context.Request.Files[0];
                                picture = new byte[file.InputStream.Length];
                                file.InputStream.Read(picture, 0, (int)file.InputStream.Length);
                                cmd.Parameters.AddWithValue("@Picture", System.Data.SqlDbType.Binary).Value = picture;
                            }
                            if (context.Request.Form["fname"] != "")
                            {
                                if (!LinkToDatabase.CheckInput(context.Request.Form["fname"], "3"))
                                {
                                    type = "0";
                                    break;
                                }
                            }
                            if (context.Request.Form["lname"] !="")
                            {
                                if (!LinkToDatabase.CheckInput(context.Request.Form["lname"], "3"))
                                {
                                    type = "0";
                                    break;
                                }
                            }
                            if (context.Request.Form["email"] !="")
                            {
                                if (!LinkToDatabase.CheckInput(context.Request.Form["email"], "4"))
                                {
                                    type = "0";
                                    break;
                                }
                            }
                            if (context.Request.Form["phone"] !=""){
                                if (!LinkToDatabase.CheckInput(context.Request.Form["phone"], "2"))
                                {
                                    type = "0";
                                    break;
                                }
                            }
                            cmd.Parameters.AddWithValue("@Fname ", context.Request.Form["fname"]);
                            cmd.Parameters.AddWithValue("@Lname ", context.Request.Form["lname"]);
                            cmd.Parameters.AddWithValue("@Phone", context.Request.Form["phone"]);
                            cmd.Parameters.AddWithValue("@Email", context.Request.Form["email"]);
                            //output
                            cmd.Parameters.Add(Result);
                         break;
                    //3=======================================================================
                    case "3":
                         if (!LinkToDatabase.CheckInput(context.Request.Form["password"], "1"))
                         {
                             type = "0";
                             break;
                         }
                        cmd = new SqlCommand(strcmd, conn);
                        cmd.CommandType = CommandType.Text;
                        Random i = new Random(Guid.NewGuid().GetHashCode());
                        int random = i.Next(0, 9999999);
                        string password = FormsAuthentication.HashPasswordForStoringInConfigFile(context.Request.Form["password"] + random.ToString(), "sha1");
                        //input
                        cmd.Parameters.AddWithValue("@Password", password);
                        cmd.Parameters.AddWithValue("@Random", random);
                        cmd.Parameters.AddWithValue("@Id", UserId);/*testid***************************最後要修改*/
                        //output
                        cmd.Parameters.Add(Result);
                        break;
                }
                DataSet ds = new DataSet();
                switch (type)
                {
                    //1=======================================================================
                    case "1":
                        da.Fill(ds, "data");
                        context.Response.ContentType = "application/json";
                        context.Response.Write(JsonConvert.SerializeObject(ds));
                        break;
                    //23=======================================================================
                    case "2":
                    case "3":
                        try{
                            conn.Open();
                            cmd.ExecuteNonQuery();
                            context.Response.ContentType = "text/plain";
                            if (Convert.ToBoolean(Result.Value)){
                                context.Response.Write("True");
                            }
                            else{
                                context.Response.Write("False");
                            }
                        }
                        catch{
                            context.Response.Write("False");//傳context.Request.Form[""]不需加單引號
                        }
                        cmd.Dispose();
                        break;  
                }
                conn.Close();
            }
        }
    }
 
    public bool IsReusable {
        get {
            return false;
        }
    }

}